/*
** realloc.c for realloc in /home/seth/malloc/tmp1
** 
** Made by kevin lansel
** Login   <lansel_k@epitech.net>
** 
** Started on  Tue Feb  5 22:49:22 2013 kevin lansel
** Last update Thu Feb  7 12:15:54 2013 florian dewulf
*/

#include	<string.h>
#include	<unistd.h>
#include	"malloc.h"

extern t_malloc	*g_list;

void		*prev_equal(t_malloc *ptr)
{
  t_malloc	*tmp;

  tmp = ptr->prev;
  ptr->prev->next = ptr->next;
  if (ptr->next)
    ptr->next->prev = ptr->prev;
  ptr->prev->state = TRUE;
  ptr->prev->size += ptr->size;
  memcpy((ptr->prev + 1), (ptr + 1), ptr->size);
  return (tmp);
}

void	*next_equal(t_malloc *ptr)
{
  t_malloc	*tmp;

  tmp = ptr->next;
  ptr->size += ptr->next->size;
  if (ptr->next->next)
    ptr->next->next->prev = ptr;
  ptr->next = ptr->next->next;
  return (tmp);
}

void		*prev_split(t_malloc *prev, t_malloc *ptr, unsigned int size)
{
  t_malloc	*new;
  void		*tmp;
  unsigned int	ptrsize;
  t_malloc	*ptrnext;

  tmp = prev;
  tmp += size + BLOCK;
  new = tmp;
  tmp = prev + 1;
  ptrsize = ptr->size;
  ptrnext = ptr->next;
  memcpy(tmp, ptr + 1, ptrsize);
  new->state = FALSE;
  new->size = (prev->size + BLOCK + ptrsize) -\
    (size + BLOCK);
  prev->size = size;
  prev->next = new;
  if (ptrnext)
    ptrnext->prev = new;
  new->next = ptrnext;
  prev->state = TRUE;
  return (tmp);
}

void		*next_split(t_malloc *ptr, t_malloc *after, unsigned int size)
{
  t_malloc	*new;
  void		*tmp;

  tmp = ptr;
  tmp += size + BLOCK;
  new = tmp;
  tmp = ptr + 1;
  new->state = FALSE;
  new->size = (ptr->size + BLOCK + after->size) -\
    (size + BLOCK);
  new->next = after->next;
  new->prev = ptr;
  ptr->size = size;
  if (after->next)
    after->next->prev = new;
  return (tmp);
}

void		*where_maille(t_malloc *p, unsigned int size)
{
  t_malloc	*tmp;

  if ((tmp = g_list) == NULL)
    return (NULL);
  while (tmp && (tmp->state == TRUE || tmp->size < size))
    tmp = tmp->next;
  if (!tmp)
    return (NULL);
  if (tmp->state == FALSE && tmp->size == size)
    {
      memcpy(tmp + 1, p + 1, size);
      p->state = FALSE;
      tmp->state = TRUE;
      joint(p);
      return (tmp);
    }
  else if (tmp->state == FALSE && tmp->size >= (size + BLOCK + 4))
    return (tool_where(tmp, size) + 1);
  else
    return (alloc(p, size));
}
